/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.juick.mod;

import com.juick.mod.api.JuickMessage;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HeaderViewListAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.net.URLEncoder;

/**
 *
 * @author ugnich
 */
public class ThreadActivity extends ListActivity implements OnItemClickListener, View.OnClickListener {

    private static final int MENUITEM_REFRESH = 2;
    private JuickMessagesAdapter listAdapter;
    private View viewLoading;
    private TextView tvReplyTo;
    private EditText etMessage;
    private Button bSend;
    private int mid = 0;
    private int rid = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent i = getIntent();
        mid = i.getIntExtra("mid", 0);
        if (mid == 0) {
            finish();
        }
        setTitle("#" + mid);

        setContentView(R.layout.thread);
        tvReplyTo = (TextView) findViewById(R.id.textReplyTo);
        etMessage = (EditText) findViewById(R.id.editMessage);
        bSend = (Button) findViewById(R.id.buttonSend);
        bSend.setOnClickListener(this);
        
        initAdapter();
    }

    private void initAdapter() {
    	getListView().setBackgroundColor(MainActivity.backgroundColor);
    	getListView().setCacheColorHint(0x00000000);
    	getListView().setDividerHeight(MainActivity.dividerHeight);
        getListView().setAdapter(new HeaderViewListAdapter(null, null, null));

        viewLoading = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listitem_loading, null);
        int count = getListView().getCount();
        if (count < 1) {
        	getListView().addFooterView(viewLoading, null, false);
        }

        listAdapter = new JuickMessagesAdapter(this);
        getListView().setAdapter(listAdapter);

        getListView().setOnItemClickListener(this);
        getListView().setOnItemLongClickListener(new JuickMessageMenu(this));

        Thread thr = new Thread(new Runnable()
        {
            public void run() 
            {
                final String jsonStr = MainActivity.getJSON(ThreadActivity.this, "http://api.juick.com/thread?mid=" + mid);
                ThreadActivity.this.runOnUiThread(new Runnable()
                {
                    public void run() 
                    {
                        if (jsonStr != null) 
                        {
                            listAdapter.parseJSON(jsonStr);
                        }
                        ThreadActivity.this.getListView().removeFooterView(viewLoading);
                    }
                });
            }
        });
        thr.start();
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        if (menu.findItem(MENUITEM_REFRESH) == null) {
            menu.add(Menu.NONE, MENUITEM_REFRESH, Menu.NONE, R.string.Refresh).setIcon(android.R.drawable.ic_menu_rotate);
        }
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == MENUITEM_REFRESH) {
            initAdapter();
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }
    }

    private void resetForm() {
        rid = 0;
        tvReplyTo.setVisibility(View.GONE);
        etMessage.setText("");
        etMessage.setEnabled(true);
        bSend.setEnabled(true);
    }

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        JuickMessage jmsg = (JuickMessage) parent.getItemAtPosition(position);
        rid = jmsg.RID;
        if (rid > 0) {
            SpannableStringBuilder ssb = new SpannableStringBuilder();
            String inreplyto = getResources().getString(R.string.In_reply_to_) + " ";
            ssb.append(inreplyto + jmsg.Text);
            ssb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, inreplyto.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            tvReplyTo.setText(ssb);
            tvReplyTo.setVisibility(View.VISIBLE);
        } else {
            tvReplyTo.setVisibility(View.GONE);
        }
    }

    public void onClick(View view) {
        String msg = etMessage.getText().toString();
        if (msg.length() < 3) {
            Toast.makeText(this, R.string.Enter_a_message, Toast.LENGTH_SHORT).show();
            return;
        }
        Toast.makeText(this, R.string.Please_wait___, Toast.LENGTH_SHORT).show();

        String msgnum = "#" + mid;
        if (rid > 0) {
            msgnum += "/" + rid;
        }
        final String body = msgnum + " " + msg;

        etMessage.setEnabled(false);
        bSend.setEnabled(false);

        Thread thr = new Thread(new Runnable() {

            public void run() {
                try {
                    final String ret = MainActivity.postJSON(ThreadActivity.this, "http://api.juick.com/post", "body=" + URLEncoder.encode(body, "utf-8"));
                    ThreadActivity.this.runOnUiThread(new Runnable() {

                        public void run() {
                            if (ret != null) {
                                Toast.makeText(ThreadActivity.this, R.string.Message_posted, Toast.LENGTH_SHORT).show();
                                resetForm();
                                initAdapter();
                            } else {
                                Toast.makeText(ThreadActivity.this, R.string.Error, Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                } catch (Exception e) {
                    Log.e("postComment", e.toString());
                }
            }
        });
        thr.start();
    }
}
